package com.cd.javacxy.module.web.controller;

import com.cd.javacxy.common.annotation.RequireLogin;
import com.cd.javacxy.common.model.entity.CxyAttachment;
import com.cd.javacxy.common.model.entity.CxyKnowledge;
import com.cd.javacxy.common.model.entity.SessionUser;
import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.query.KnowledgeQuery;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import com.cd.javacxy.common.utils.CategoryCache;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.common.utils.PageResult;
import com.cd.javacxy.exception.BussinessException;
import com.cd.javacxy.module.base.BaseController;
import com.cd.javacxy.module.web.service.CxyKnowledgeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * CxyKnowledge的路由接口服务
 *
 * @author yanghy
 */
@Controller
@RequestMapping("/knowledge")
@Slf4j
public class CxyKnowledgeController extends BaseController {

    /**
     * CxyKnowledgeService服务
     */
    private CxyKnowledgeService cxyKnowledgeService;

    private CategoryCache categoryCache;

    @Autowired
    public void setCxyKnowledgeService(CxyKnowledgeService cxyKnowledgeService) {
        this.cxyKnowledgeService = cxyKnowledgeService;
    }

    @Autowired
    public void setCategoryCache(CategoryCache categoryCache) {
        this.categoryCache = categoryCache;
    }

    @GetMapping
    public ModelAndView knowledge(KnowledgeQuery knowledgeQuery) {
        ModelAndView view = new ModelAndView("knowledge/knowledge");
        PageResult<CxyKnowledge> pageResult = this.cxyKnowledgeService.findKnowledgeByPage(knowledgeQuery);
        view.addObject("categories", categoryCache.getKnowledgeCategories());
        view.addObject("result", pageResult);
        return view;
    }

    @GetMapping("/{knowledgeId}")
    public ModelAndView knowledgeDetail(@PathVariable Integer knowledgeId, HttpSession session) {
        ModelAndView view = new ModelAndView("knowledge/knowledge_detail");
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        Integer userId = null;
        try {
            userId = sessionUser == null ? null : sessionUser.getUserId();
            CxyKnowledge topic = this.cxyKnowledgeService.showKnowledge(knowledgeId, userId);
            view.addObject("topic", topic);
        } catch (Exception e) {
            log.error("文章加载出错", e);
            view.setViewName("redirect:" + Constants.ERROR_404);
        }
        return view;
    }

    @ResponseBody
    @GetMapping("/list")
    public AjaxResponse<Object> loadKnowledge(KnowledgeQuery knowledgeQuery) {
        AjaxResponse<Object> ajaxResponse = AjaxResponse.builder().build();
        try {
            PageResult<CxyKnowledge> pageResult = this.cxyKnowledgeService.findKnowledgeByPage(knowledgeQuery);
            ajaxResponse.setData(pageResult);
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (Exception e) {
            log.error("加载知识库异常", e);
            ajaxResponse.setErrorMsg("加载知识库出错");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
        }
        return ajaxResponse;
    }

    @GetMapping(value = "/pCategoryId/{pCategoryId}")
    public ModelAndView pCategoryId(@PathVariable Integer pCategoryId, KnowledgeQuery knowledgeQuery) {
        ModelAndView view = new ModelAndView("knowledge/knowledge");
        PageResult<CxyKnowledge> pageResult = this.cxyKnowledgeService.findKnowledgeByPage(knowledgeQuery);
        view.addObject("categories", categoryCache.getKnowledgeCategories());
        view.addObject("KnwoledgeTitleCategory", CategoryCache.getCategoryById(pCategoryId));
        view.addObject("result", pageResult);
        return view;
    }

    @GetMapping(value = "/categoryId/{categoryId}")
    public ModelAndView categoryId(@PathVariable Integer categoryId, KnowledgeQuery knowledgeQuery) {
        ModelAndView view = new ModelAndView("knowledge/knowledge");
        PageResult<CxyKnowledge> pageResult = this.cxyKnowledgeService.findKnowledgeByPage(knowledgeQuery);
        view.addObject("categories", categoryCache.getKnowledgeCategories());
        view.addObject("KnwoledgeTitleCategory", CategoryCache.getCategoryById(categoryId));
        view.addObject("result", pageResult);
        return view;
    }

    @GetMapping("/prePublicKnowledge")
    //@RequireLogin
    public ModelAndView prePublicknowledge() {
        return new ModelAndView("knowledge/publicKnowledge");
    }

    @RequireLogin
    @ResponseBody
    @PostMapping("/publish")
    public AjaxResponse<Integer> publicKnowledge(HttpSession session, CxyKnowledge knowledge, CxyAttachment attachment) {
        AjaxResponse<Integer> ajaxResponse = AjaxResponse.<Integer>builder().build();
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        try {
            this.setUserBaseInfo(CxyKnowledge.class, knowledge, session);
            this.cxyKnowledgeService.addKnowledge(knowledge, attachment);
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
            ajaxResponse.setData(knowledge.getTopicId());
        } catch (BussinessException e) {
            ajaxResponse.setErrorMsg(e.getLocalizedMessage());
            ajaxResponse.setCode(ResponseCode.BUSSINESSERROR.getCode());
            log.error("{}投稿失败", sessionUser.getUserName());
        } catch (Exception e) {
            ajaxResponse.setErrorMsg("服务器出错,投稿失败");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
            log.error("{}投稿失败", sessionUser.getUserName());
        }
        return ajaxResponse;
    }
}
